package com.sun.module_home.ui.questions

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.sun.module_base.app.BaseViewModel
import com.sun.module_base.app.ResultState
import com.sun.module_common.model.Article
import com.sun.module_common.model.ListWrapper
import com.sun.module_home.net.HttpRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject

/**
 *@author:sunc
 *@time :2025/8/1 16:00
 *@desc: 问答
 */
@HiltViewModel
class QuestionsViewModel @Inject constructor(private val httpRepository: HttpRepository) :
    BaseViewModel() {

    private val _articleFlow =
        MutableStateFlow<ArticleState>(ResultState.Loading())
    val articleFlow = _articleFlow.asStateFlow()

    var page by mutableIntStateOf(0)

    private val _isRefresh = mutableStateOf(false)
    val isRefresh: Boolean get() = _isRefresh.value

    private val _isLoadMore = mutableStateOf(false)
    val isLoadMore: Boolean get() = _isLoadMore.value


    init {
        refresh()
    }

    fun getArticleList() {
        launchUI({ httpRepository.getWendaList(page) }, _articleFlow, onCompletion = {
            _isRefresh.value = false
            _isLoadMore.value = false
        })
    }

    fun refresh() {
        _isRefresh.value = true
        page = 0
        getArticleList()
    }


    fun loadMore() {
        _isLoadMore.value = true
        page++
        getArticleList()
    }

}
//包不同，允许取相同名字
typealias ArticleState = ResultState<ListWrapper<Article>?>